import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { GUI } from 'lil-gui';
import doorTextureUrl from '@/assets/texture/doorTexture.jpeg';

const guiParams = {
  color: 0xff0000,
};

export default function index() {
  const mountRef = useRef(null);
  const gui = new GUI();

  useEffect(() => {
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      1,
      1000
    );
    camera.position.set(1, 1, 5);
    scene.add(camera);

    const count = 50;
    const arrays = new Float32Array(count * 3 * 3);
    for (let i = 0; i < count * 3 * 3; i++) {
      arrays[i] = (Math.random() - 0.5) * 4;
    }
    const bufferAttribute = new THREE.BufferAttribute(arrays, 3);
    const bufferGeometry = new THREE.BufferGeometry();
    bufferGeometry.setAttribute('position', bufferAttribute);
    const meterial = new THREE.MeshBasicMaterial({ color: guiParams.color });
    const bufferMesh = new THREE.Mesh(bufferGeometry, meterial);
    scene.add(bufferMesh);

    const textureLoader = new THREE.TextureLoader();
    const texture = textureLoader.load(doorTextureUrl);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    mountRef.current.appendChild(renderer.domElement);
    renderer.render(scene, camera);

    const axis = new OrbitControls(camera, renderer.domElement);

    // gui
    gui.add(bufferMesh.position, 'y').min(-3).max(3).step(0.1);
    gui.add(bufferMesh.position, 'x').min(-3).max(3).step(0.1);
    gui.add(bufferMesh.position, 'z').min(-3).max(3).step(0.1);

    gui.addColor(guiParams, 'color').onChange(() => {
      meterial.color.set(guiParams.color);
    });
    gui.add(bufferMesh, 'visible');
    gui.add(meterial, 'wireframe');

    const animation = () => {
      axis.update();
      renderer.render(scene, camera);
      window.requestAnimationFrame(animation);
    };
    animation();
  }, []);

  return (
    <div
      ref={mountRef}
      style={{ width: '100%' }}
    />
  );
}
